package cn.yzj.openapi.utils;

import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * 字符串工具类
 *
 * @author gzkemays
 * @since 2021/11/18 17:54
 */
public class StrUtils {
  private static final String HTTP = "http";
  private static final String HTTPS = "https";
  private static final String WWW = "www.";

  /**
   * 是否为 web
   *
   * @param url 地址
   * @return 判断结果
   */
  public static boolean isWeb(String url) {
    return (url.startsWith(HTTP) || url.startsWith(HTTPS) || url.startsWith(WWW));
  }

  public static <T> String listToStr(List<T> list, String separator) {
    StringJoiner sj = new StringJoiner(separator);
    for (Object o : list) {
      sj.add(String.valueOf(o));
    }
    return sj.toString();
  }
  @SuppressWarnings("unchecked")
  public static <T> List<T> strToList(String str, String sequence, Class<T> clazz) {
    if (StringUtils.hasText(str)) {
      String[] split = str.split(sequence);
      return Arrays.stream(split).map(s -> (T) s).collect(Collectors.toList());
    }
    return new ArrayList<>();
  }

  public static String getLastSplitHasSplitAfterStr(String str, String split) {
    return getLastSplitAfterStr(str, split, true);
  }

  public static String getLastSplitAfterStr(String str, String split) {
    return getLastSplitAfterStr(str, split, false);
  }

  /**
   * 获取 split 后续文字
   *
   * @param str 字符串
   * @param split 指定符号
   * @return 后续文字
   */
  private static String getLastSplitAfterStr(String str, String split, boolean hasSplit) {
    if (str != null && str.length() > 0) {
      int splitIndex = hasSplit ? str.lastIndexOf(split) : str.lastIndexOf(split) + 1;
      if (splitIndex > -1 && splitIndex < str.length() - 1) {
        return str.substring(splitIndex);
      }
    }
    return null;
  }
}
